<?php
/**
 * 代理管理员
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\AgentShop;
use app\common\service\AgentAdminService;

class Agentadmin extends Api {
	
	/**
	 * 管理员列表
	 */
	public function index() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level != \app\admin\model\User::LEVEL_HEADQUARTERS) {
			$agentInfo = \app\common\model\User::getUserAgentInfo($userId);
			!$agentInfo && $this->error('你不是代理商');
			
			$agentId = $agentInfo['id'];
		} else {
			$agentId = 0;
		}
		
		$model = new \app\common\model\AgentAdmin();
		$admins = $model->getAdminListByAgentId($agentId);
		$this->success('查询成功', $admins);
	}
	
	
	/**
	 * 加入
	 */
	public function join() {
		
		$agentUid = $this->request->get('uid');
		!$agentUid && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		$level = $this->auth->level;
		if($level != \app\admin\model\User::LEVEL_USER) {
			$this->error('你已有其它身份，不能成为管理员');
		}
		
		$service = new AgentAdminService();
		$res = $service->join($agentUid, $userId);
		if($res === true) {
			$this->success('加入成功,等待审核');
		} else {
			$this->error($res);
		}
		
	}
	
	/**
	 * 更改状态
	 */
	public function changeStatus() {
		$id = $this->request->get('id');
		$status = $this->request->get('status', 0, 'intval');
		if(!$id){
			$this->error('参数错误');
		}
		
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == \app\admin\model\User::LEVEL_HEADQUARTERS) {
			$agentId = 0;
		} else {
			$agent = AgentShop::get(['user_id' => $userId]);
			!$agent && $this->error('你不是代理');
			
			$agentId = $agent['id'];
		}
		
		$row = \app\common\model\AgentAdmin::get(['id' => $id, 'agent_id' => $agentId]);
		!$row && $this->error('非法操作');
		
		$model = new \app\common\model\AgentAdmin();
		$res = $model->changetStatus($id, $agentId, $status);
		if($res !== false) {
			$this->success('操作成功');
		} else {
			$this->error('操作出错');
		}
	}
	
	
}
